package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/4/5 20:18
 * https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof/
 */
public class Sword12 {

    int n, m;
    public boolean exist(char[][] board, String word) {
        n = board.length;
        m = board[0].length;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                //找起点
                if (board[i][j] == word.charAt(0)) {
                    boolean flag = dfs(board, word, i, j, 0);
                    if (flag) {
                        return flag;
                    }
                }
            }
        }
        return false;
    }

    private boolean dfs(char[][] board, String word, int i, int j, int wordIndex) {
        if (i < 0 || i >= n || j < 0 || j >= m || board[i][j] == '1' || board[i][j] != word.charAt(wordIndex)) {
            return false;
        }
        if (wordIndex == word.length() - 1) {
            return true;
        }
        char temp = board[i][j];
        board[i][j] = '1';
        wordIndex++;
        boolean res = dfs(board, word, i - 1, j, wordIndex) || dfs(board, word, i + 1, j, wordIndex) || dfs(board, word, i, j + 1, wordIndex) ||
                dfs(board, word, i, j - 1, wordIndex);
        board[i][j] = temp;
        return res;
    }

    public static void main(String[] args) {

    }
}
